from system.object import Object
from system.eventServer import eventServer

class Sizer(Object):
    def __init__(self, parent, type = None, name = None):
        Object.__init__(self, parent, type, name)
        
        self.defaultVar("renderOp2d","sceneNode")
        self.defaultVar("layoutType","horiz")
        self.defaultVar("initLayout",True)
        
        if self.getVar("initLayout"):
            self.layout()
        
        eventServer.register("sizerLayout",self.sizerLayout)
        
    def sizerLayout(self, cmd, args):
        if args['path'] == self.getVar("path"):
            if args.has_key('layoutType'):
                self.layout(args['layoutType'])
            else:
                self.layout()
        
    def layout(self, layoutType = None):
        if layoutType:
            self.setVar("layoutType",layoutType)
        
        funcName = "layout_%s" % self.getVar("layoutType")
        if hasattr(self,funcName) and callable(getattr(self,funcName)):
            getattr(self,funcName)()
            
    def layout_horiz(self):
        children = self.children.values()
        count = len(children)
        size = 1.0 / count
        
        for i, child in enumerate(children):
            child.setVar("pos",(i*size,0))
            child.setVar("scale",(size,1))

    def layout_vert(self):
        children = self.children.values()
        count = len(children)
        size = 1.0 / count
        
        for i, child in enumerate(children):
            child.setVar("pos",(0,i*size))
            child.setVar("scale",(1,size))
